package com.example.auto;

import java.lang.reflect.Method;

import android.hardware.input.InputManager;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Message;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;

public class InputInjector implements Callback {
	private static final InputInjector INSTANCE = new InputInjector();
	private static InputManager im;
	private static Method injectInputEventMethod;

	protected HandlerThread handlerThread;
	protected Handler handler;
	static final AbsInput input = new AbsInput() {

		private void injectEvent(InputEvent event) {
			try {
				// InputManager.getInstance().injectInputEvent(event,2);
				injectInputEventMethod.invoke(im, event, 2);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected void injectMotionEvent(MotionEvent event) {
			injectEvent(event);
		}

		@Override
		protected void injectKeyEvent(KeyEvent event) {
			injectEvent(event);
		}
	};

	private InputInjector() {
		handlerThread = new HandlerThread("");
		handlerThread.start();
		handler = new Handler(handlerThread.getLooper(), this);
		try {
			Class<?> clazz = InputManager.class;
			Method method = clazz.getDeclaredMethod("getInstance");
			im = (InputManager) method.invoke(null);
			injectInputEventMethod = clazz.getDeclaredMethod(
					"injectInputEvent", InputEvent.class, int.class);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		return false;
	}

	public static InputInjector getInstance() {
		return INSTANCE;
	}

	public void sendSwipe(int delay, final float x1, final float y1,
			final float x2, final float y2, final int duration) {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				input.sendSwipe(x1, y1, x2, y2, duration);
			}
		}, delay);
	}

	public void sendTap(int delay, final float x, final float y) {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				input.sendTap(x, y);
			}
		}, delay);
	}

	public void sendKey(int delay, final int keyCode) {
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				input.sendKeyEvent(keyCode);
			}
		}, delay);
	}
}
